package com.laivi.basic.module.orm;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import com.laivi.basic.module.log.Log;
import com.laivi.basic.module.log.Logs;
import com.laivi.basic.util.LangUtil;

/**
 * @author laivi.zhu@gmail.com
 * @date 2014-7-7
 * description:
 */
public class ORM {
	private static Log log=Logs.getLog(ORM.class);

	public static <T> T orm(Map<String,Object> value,Class<T> klass){
		T obj=null;
		try {
			obj=klass.newInstance();
			for(Field field:LangUtil.getFields(klass)){
				try{
					field.setAccessible(true);
					field.set(obj, value.get(field.getName()));
				}catch(Exception e){
					log.error("set Field:"+field.getName()+" error!");
				}finally{
					field.setAccessible(false);
				}
			}
		} catch (InstantiationException e) {
			log.error("instantiation obj error:"+e.getMessage());
		} catch (IllegalAccessException e) {
			log.error("illegal access error:"+e.getMessage());
		}
		return obj;
	}
	
	public static <T> Map<String,Object> mor(T obj){
		Map<String,Object> map=new HashMap<String,Object>();
		for(Field field:LangUtil.getFields(obj.getClass())){
			try {
				field.setAccessible(true);
				Object value=field.get(obj);
				map.put(field.getName(), value);
			} catch (IllegalArgumentException e) {
				log.error("illegal argument:"+e.getMessage());
			} catch (IllegalAccessException e) {
				log.error("illegal access error:"+e.getMessage());
			}finally{
				field.setAccessible(false);
			}
		}
		return map;
	}
}
